package com.user.query.pay.controller;


import com.user.query.pay.pojo.CrowdVo;
import com.user.query.pay.utils.alipay.config.AlipayConfig;
import com.user.query.pay.utils.alipay.util.AlipayCore;
import com.user.query.pay.utils.alipay.util.AlipayNotify;
import com.user.query.utils.HttpCode;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by bgt on 2016/7/12.
 */
 @Controller
 @RequestMapping("/webusercrowd")
public class WebUserCrowdController  {
    protected Logger log = Logger.getLogger(getClass());
    

    /**
     * pay
     * @param request
     * @param map
     * @return
     */
    @RequestMapping(value = "/pay",method = RequestMethod.GET)
    public String pay(HttpServletRequest request, ModelMap map){
        String msg="添加";
        String crowdId=request.getParameter("crowdId");
        String crowdPrice=request.getParameter("crowdPrice");
        try {
            CrowdVo vo=new CrowdVo();
            vo.setId(crowdId);
            vo.setBody("众筹神秘导师。");
            vo.setIp("ipdizhi");
            vo.setName("神秘导师");
            vo.setMoney(crowdPrice);
            vo.setType("4");
            map.put("vo", vo);
            request.setAttribute("vo",vo);
            request.setCharacterEncoding("UTF-8");
            request.setAttribute("out_trade_no",vo.getId());
            request.getSession().setAttribute("out_trade_no",vo.getId());
            request.setAttribute("subject",vo.getName());
            request.setAttribute("total_fee",vo.getMoney());
            request.setAttribute("body",vo.getBody());
            request.setAttribute("exter_invoke_ip",vo.getIp());
            request.setAttribute("extra_common_param",vo.getType());
            map.put("code", HttpCode.HTTP_CODE_200);
            map.put("msg", msg+"初始化");
        } catch (Exception e) {
            map.put("code", HttpCode.HTTP_CODE_500);
            map.put("msg", msg+"初始化失败！");
        }
        return "alipay/crow";
    }
    /**
     * pay
     * @param request
     * @param map
     * @return
     */
    @RequestMapping(value = "/returnurl",method = RequestMethod.GET)
    public String returnurl(HttpServletRequest request, HttpServletResponse response, ModelMap map){
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        String out_trade_no = new String(request.getParameter("out_trade_no"));

        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no"));

        //交易状态
        String trade_status = new String(request.getParameter("trade_status"));

        //交易人民币金额
        String total_fee = new String(request.getParameter("total_fee"));

        //公用回传参数（1：购买	2：职业咨询悬赏	3：行业咨询提问）
        String extra_common_param = new String(request.getParameter("extra_common_param"));

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//

        //计算得出通知验证结果
        boolean verify_result = AlipayNotify.verify(params);

        if(verify_result){//验证成功
            //////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码

            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
            if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
            	if(!StringUtils.isNotEmpty(extra_common_param) && extra_common_param.equals("1")) { //课程购买
    				// 跳转订单页面
    				return "forward:/";
    			} else if(!StringUtils.isNotEmpty(extra_common_param) && extra_common_param.equals("2")) { //咨询悬赏
    				// 跳转子夜咨询首页
    				return "forward:/consult/career";
    			} else if(!StringUtils.isNotEmpty(extra_common_param) && extra_common_param.equals("3")) { //咨询提问
    				// 跳转行业咨询首页
    				return "forward:/consult/industy";
    			}else if(!StringUtils.isNotEmpty(extra_common_param) && extra_common_param.equals("4")) { //众筹
    				// 跳转页面
                    System.out.print("进行跳转......返回商户页面cuccess");
                    return "forward:/crowd/byPage";
    			}
            }
            //////////////////////////////////////////////////////////////////////////////////////////
        }else{
            System.out.print("进行跳转......返回商户页面error");
        }
        return "forward:/crowd/byPage";
    }

    @RequestMapping(value = "/notify",method = RequestMethod.POST)
    @ResponseBody
    public void notify(HttpServletRequest request, HttpServletResponse response, ModelMap map){
        System.out.println("异步处理支付宝返回信息");
        try {
        	Map<String,String> params = new HashMap<String,String>();
            Map requestParams = request.getParameterMap();
            for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
                //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
                params.put(name, valueStr);
            }

            //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no"));

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no"));

            //交易状态
            String trade_status = new String(request.getParameter("trade_status"));

            //交易人民币金额
            String total_fee = new String(request.getParameter("total_fee"));

            //公用回传参数（1：购买	2：职业咨询悬赏	3：行业咨询提问）
            String extra_common_param = new String(request.getParameter("extra_common_param"));

            //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//

            if(AlipayNotify.verify(params)){//验证成功
                if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS"))
                	if(!StringUtils.isNotEmpty(extra_common_param) && extra_common_param.equals("1")) { //课程购买
        				// 处理课程购买相关业务逻辑


        			}

                //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

                // 通知支付宝我已收到消息，不要在次发送了
                response.getWriter().println("success");	//请不要修改或删除
                //////////////////////////////////////////////////////////////////////////////////////////
            }else{//验证失败
            	response.getWriter().println("fail");
            }
		} catch (Exception e) {
			e.printStackTrace();
			try {
				response.getWriter().println("fail");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
        
    }
    /**
     * 支付宝消息验证地址
     */
    private static final String HTTPS_VERIFY_URL = "https://mapi.alipay.com/gateway.do?service=notify_verify&";

    /**
     * 验证消息是否是支付宝发出的合法消息
     * @param params 通知返回来的参数数组
     * @param type 发起校验的来源 1 notify  2 return
     * @return 验证结果
     */
    public   boolean verify(Map<String, String> params,String type) {
        log.debug("支付宝回调校验 in");
        if (type.equals("1")) {
            log.debug("notify方式发起的校验");
        } else {
            log.debug("return方式发起的校验");
        }
        String responseTxt = "false";
        if(params.get("notify_id") != null) {
            String notify_id = params.get("notify_id");
            String partner = AlipayConfig.partner;
            String veryfy_url = HTTPS_VERIFY_URL + "partner=" + partner + "&notify_id=" + notify_id;
            log.debug("支付宝回调校验url"+veryfy_url);
            String inputLine = "";
            try {
                URL url = new URL(veryfy_url);
               /* HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection
                        .getInputStream()));
                inputLine = in.readLine().toString();*/
                StringBuffer result = new StringBuffer();
                URLConnection conn = url.openConnection();
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String line = null;
                while((line = reader.readLine()) != null)
                {
                    result.append(line);
                }
                reader.close();
                inputLine=result.toString();
                log.debug("支付宝回调校验inputLine:::"+inputLine);

                if (inputLine.equals("")) {
                    responseTxt = "false";
                } else {
                    responseTxt = "true";
                }

                log.debug("支付宝回调校验inputLine后的responseTxt的值：：：："+responseTxt);

            } catch (Exception e) {
                log.error("支付宝回调校验inputLine失败：：：：：：：：：：",e);
                inputLine = "";
                if (inputLine.equals("")) {
                    responseTxt = "false";
                } else {
                    responseTxt = "true";
                }
            }
        }
        log.debug("支付宝回调校验开始校验:sign：：：：");
        String sign = "";
        if(params.get("sign") != null) {sign = params.get("sign");}
        //过滤空值、sign与sign_type参数
        Map<String, String> sParaNew = AlipayCore.paraFilter(params);
        //获取待签名字符串
        String preSignStr = AlipayCore.createLinkString(sParaNew);
        log.debug("支付宝回调校验 sign开始校验：：：：");
        //获得签名验证结果
        boolean isSign = false;
        if(AlipayConfig.sign_type.equals("MD5") ) {
            isSign = com.user.query.pay.utils.alipay.sign.MD5.verify(preSignStr, sign, AlipayConfig.key, AlipayConfig.input_charset);
        }
        log.debug("支付宝回调校验sign结束：：：："+isSign);
        if (isSign && responseTxt.equals("true")) {
            log.debug("responseTxt::"+responseTxt);
            log.debug("isSign::"+isSign);
            return true;
        } else {
            log.debug("else的情况responseTxt::"+responseTxt);
            log.debug("同上isSign::"+isSign);
            return false;
        }
    }
}
